package loader;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class LoaderXml extends DefaultHandler {
	protected SAXParser parser;

	protected String xml_path;

	protected StringBuffer text_atual = new StringBuffer();

	protected StringBuffer current_path_node = new StringBuffer();

	protected Map<String, Integer> path_ids = new HashMap<String, Integer>();

	protected int lastPathIdCreated = 0;

	public LoaderXml() throws ParserConfigurationException, SAXException {
		parser = SAXParserFactory.newInstance().newSAXParser();
	}

	public void Load(String xml_path) throws SAXException, IOException, SQLException {
		this.setXml_path(xml_path);

		parser.parse(getXml_path(), this);
	}

	/************************** SAX API Events **********************/

	@Override
	public void startDocument() throws SAXException {
		// TODO Auto-generated method stub
		super.startDocument();
		System.out.println("Leitura do xml iniciada.");
	}

	@Override
	public void endDocument() throws SAXException {
		// TODO Auto-generated method stub
		super.endDocument();
		System.out.println("Leitura do xml encerrada.");
	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		// TODO Auto-generated method stub
		super.characters(ch, start, length);
		text_atual.append(ch, start, length);
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		// TODO Auto-generated method stub
		super.startElement(uri, localName, qName, attributes);
		current_path_node.append(qName + "/");
		text_atual.delete(0, text_atual.length());
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		// TODO Auto-generated method stub
		super.endElement(uri, localName, qName);

		current_path_node.delete(current_path_node.length() - qName.length()
				- 1, current_path_node.length());
	}

	/************************* GETTERS AND SETTERS ******************/
	
	protected int getPathId(String path_id) {
		if (!path_ids.containsKey(path_id)) {
			path_ids.put(path_id, lastPathIdCreated);
			lastPathIdCreated++;
		}

		return path_ids.get(path_id);
	}

	public void setXml_path(String xml_path) {
		this.xml_path = xml_path;
	}

	public String getXml_path() {
		return xml_path;
	}
}
